import {defineStore} from "pinia";
import {ref, watch} from "vue";
import {getRoleList, RoleCreate, RoleDelete, RoleUpdate} from "@/services/api/organization/role.ts";
import {useOrgStore} from "@/store/modules/organization/index.ts";
import useMessage from "@/utils/useMessage.ts";
import {hasPermission} from "@/utils/permission.ts";

export const useRoleStore = defineStore('role', ()=>{
    const dataSource = ref<PermissionRole[]>([])
    const loading = ref<boolean>(false)
    const orgStore = useOrgStore()
    const getList = async (force?:boolean)=>{
        if(!force && dataSource.value.length > 0){
            return
        }
        loading.value = true
        const res:ApiResponse<PermissionRole[]> = await getRoleList(orgStore.id)
        if(res.code === 200){
            dataSource.value = res.data
        }else {
            useMessage(500,res.message)
        }
        setTimeout(()=>loading.value = false,100)
    }
    const create = async (params:PermissionRoleForm)=>{
        if (!hasPermission('role:create')) return false;
        const res = await RoleCreate(params)
        if(res.code === 200){
            await getList(true)
        }
        useMessage(res.code,res.message)
        return res.code === 200
    }
    const update = async (params:PermissionRoleForm)=>{
        if (!hasPermission('role:update')) return false;
        if (!params.id){
            useMessage(500,'请选择要修改的角色')
            return false
        }
        const res = await RoleUpdate(params.id,params)
        if (res.code === 200){
            const item = dataSource.value.find(item=>item.id === params.id)
            if (item){
                Object.assign(item,params)
            }
        }
        useMessage(res.code,res.message)
        return res.code === 200
    }
    const remove = async (id:number)=>{
        if (!hasPermission('role:delete')) return false;
        const res = await RoleDelete(id)
        if (res.code === 200){
            dataSource.value = dataSource.value.filter(item=>item.id !== id)
        }
        useMessage(res.code,res.message)
        return res.code === 200
    }
    watch(()=>orgStore.id,async ()=>{
        await getList(true)
    })
    return {dataSource,loading,getList,create,update,remove}
})